const { Comments, sequelize } = require('../models')
module.exports = [
  {
    /**
     * @api {post} /api/comment/list [评论列表]
     * @apiGroup Comments
     * @apiPermission none
     * @apiParam  {Number} articleId 文章Id
     * @apiParam  {Number} [offset=0]
     * @apiParam  {Number} [limit=10]
     *
     */
    url: '/api/comment/list',
    method: 'post',
    request: async (req, res) => {
      try {
        const { articleId, offset, limit } = req.body
        if (!articleId) return res.json({msg: 'articleId不能为空'})
        const result = await Comments.findAndCountAll({
          where: {
            articleId: articleId
          },
          offset: Number(offset) || 0,
          limit: Number(limit) || 10
        }).catch(err => {
          console.log(err)
        })
        res.json(result)
      } catch (error) {
        res.json(error)
      }
    }
  }, {
    url: '/api/comment/:id',
    method: 'get',
    request: async (req, res) => {

    }
  }, {
    /**
     * @api {delete} /api/article/delete/:id [删除评论]
     * @apiGroup Comments
     * @apiPermission none
     * @apiParam  {Number} id 评论id
     */
    url: '/api/comment/delete/:id',
    method: 'delete',
    request: async (req, res) => {
      try {
        const { id } = req.params
        const comment = await Comments.findOne({
          where: { id }
        })
        if (!comment) return res.json({ msg: '找不到您想要的' })
        await Comments.destroy({ where: { id } })
        res.json({ msg: '删除成功', id })
      } catch (error) {
        res.json({ msg: '删除失败', error })
      }
    }
  }, {
    /**
     * @api {post} /api/comment/add [新增评论]
     * @apiGroup Comments
     * @apiPermission none
     * @apiParam  {Number} articleId 文章id
     * @apiParam  {String} content 评论内容
     * @apiParam  {Number} [userId] 用户id
     */
    url: '/api/comment/add',
    method: 'post',
    request: async (req, res) => {
      try {
        const result = await Comments.create(req.body)
        res.json({ msg: '评论成功', result })
      } catch (error) {
        res.json({ msg: '评论失败', error })
      }
    }
  }
]
